package nextee.cabletest.protocol;

/**
 * Created by Administrator on 2015/4/27.
 */
public class ProtocolHandle {
    public void setCallback(ProtocolCallback callback) {
        this.callback = callback;
    }

    public interface ProtocolCallback{
        public void handleProtocolData(byte[] raw_data);
    }

    private ProtocolCallback callback;
    private final byte[] head = {'H', 'E', 'A', 'D'};
    private int head_index=0;
    private boolean isFinded=false;
    private byte[] buf= new byte[6];
    private int    buf_index=0;

    public void push(byte[] data, int len){
        for(int i=0; i<len; i++){
            if(!isFinded) {
                if (data[i] == head[head_index++]) {

                } else {
                    head_index = 0;
                }

                if(head_index==head.length){
                    isFinded=true;
                    head_index=0;
                }
            }
            else{
                buf[buf_index++]=data[i];
                if(buf_index==buf.length){
                    buf_index=0;
                    isFinded=false;
                    if(callback==null) {
                        throw new NullPointerException("callback is null");
                    }
                    else{
                        callback.handleProtocolData(buf);
                    }
                }
            }

        }
    }
}
